package com.freedom.admin.domain.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.freedom.admin.domain.repository.SysUserRoleRepository;
import com.freedom.admin.domain.service.UserRoleService;
import com.freedom.admin.infrastructure.persistence.pojo.po.SysUserRolePO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserRoleServiceImpl implements UserRoleService {

    private final SysUserRoleRepository userRoleRepository;

    @Override
    public void save(Integer userId, List<Integer> roleIds) {
        List<SysUserRolePO> userRoleList = userRoleBuilder(userId, roleIds);
        userRoleRepository.saveBatch(userRoleList);
    }

    @Override
    public void modifyByIds(Integer userId, List<Integer> roleIds) {
        List<SysUserRolePO> userRoleList = userRoleRepository.findByUserId(userId);
        if (CollUtil.isNotEmpty(userRoleList)) {
            userRoleRepository.removeByUserId(userId);
        }
        save(userId, roleIds);
    }

    @Override
    public void removeByUserIds(List<Integer> userIds) {
        userRoleRepository.removeByUserIds(userIds);
    }

    @Override
    public void removeByRoleIds(List<Integer> roleIds) {
        userRoleRepository.removeByRoleIds(roleIds);
    }

    private List<SysUserRolePO> userRoleBuilder(Integer userId, List<Integer> roleIds) {
        return roleIds.stream().map(roleId -> new SysUserRolePO(userId, roleId)).collect(Collectors.toList());
    }
}
